//
//  LZMyRestaurantInfoTableView.m
//  laziz_Merchant
//
//  Created by ZhaoDongBo on 2016/12/17.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZMyRestaurantInfoTableView.h"
#import "LZMyRestaurantInfoHeaderView.h"
#import "LZMyRestaurantInfoTableViewCell.h"
#import "LZMyRestaurantInfoTimeTableViewCell.h"
#import "LZMyRestaurantInfoTextFieldTableViewCell.h"
#import "LZGroupListTableViewCell.h"
#import "Masonry.h"
#import "LZMerchantInfoModel.h"
#import "extobjc.h"
#import "LZMainPhotosOperationTableViewCell.h"
#import "XXNibConvention.h"
#import "MJPhotoBrowser.h"
#import "LZManagePicturePresenter.h"
#import "LZUserModel.h"
#import "LZActionSheet.h"
#import "LZImagePickerManager.h"
#import "LZUploadImagePresenter.h"
#import "LZAlertView.h"
#import "MBProgressHUD.h"
#import "LZManagePicturesViewController.h"


@interface LZMyRestaurantInfoTableView() <UITableViewDelegate, UITableViewDataSource,LZPictureManagerDelegate>

@property (strong, nonatomic) LZMainPhotosOperationTableViewCell *mainPhotosCell;


@property (strong, nonatomic) MJPhotoBrowser *brower;


@property (strong, nonatomic) NSMutableArray<NSDictionary *> *mainPhotos;


@property (weak, nonatomic) LZActionSheet *actionSheet;


@property (strong, nonatomic) LZImagePickerManager *pictureManager;


@property (strong, nonatomic) UIImage *resultImage;

@end

@implementation LZMyRestaurantInfoTableView

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        [self setup];
    }
    return self;
}

#pragma
#pragma mark private method

- (LZMyRestaurantInfoHeaderView *)headerView {
    if (_headerView == nil) {
        _headerView = [[LZMyRestaurantInfoHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 55)];
    }
    return _headerView;
}

- (LZActionSheet *)actionSheet {
    if (_actionSheet == nil) {
        LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _actionSheet = sheet;
        [_actionSheet creatHeaderWithTitle:LZLocalizedString(@"res_auth_choose_img_sheet_title", nil) andHeight:51];
        [[UIApplication sharedApplication].keyWindow addSubview:_actionSheet];
        
        @weakify(self)
        _actionSheet.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
            @strongify(self)
            if (indexPath.section == 0) {
                UIImagePickerControllerSourceType sourceType = 0;
                switch (indexPath.row) {
                    case 0:
                    {
                        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                            sourceType = UIImagePickerControllerSourceTypeCamera;
                        }else{
                            return;
                        }
                    }
                        break;
                    case 1:
                    {
                        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                        }else{
                            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                        }
                    }
                        break;
                    case 2:
                    {
                        LZManagePicturesViewController *vc = [[LZManagePicturesViewController alloc] initWithNibName:@"LZManagePicturesViewController" bundle:nil];
                        
                        [vc setSelectPictureBlock:^(NSString *imageUrl) {
                            @strongify(self)
                            imageUrl = [imageUrl stringByReplacingOccurrencesOfString:APIBaseImageUrl withString:@""];
                            [self addPicture:imageUrl];
                        }];
                        
                        UINavigationController *currentNavigationVC = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;

                        [currentNavigationVC pushViewController:vc animated:YES];
                        
                        return;
                    }
                        break;
                    default:
                        return;
                }
                
                [self.pictureManager choosePictureWithSourceType:sourceType andPresenterVC:[UIApplication sharedApplication].keyWindow.rootViewController];
            }
        };
    }
    
    return _actionSheet;
}


- (LZImagePickerManager*)pictureManager {
    if (_pictureManager) {
        return _pictureManager;
    }
    LZImagePickerManager *manager = [[LZImagePickerManager alloc] init];
    manager.allowsEditing = NO;
    manager.delegate = self;
    _pictureManager = manager;
    return _pictureManager;
}



-(LZMainPhotosOperationTableViewCell *)mainPhotosCell{
    if (!_mainPhotosCell) {
        _mainPhotosCell = [[NSBundle mainBundle] loadNibNamed:@"LZMainPhotosOperationTableViewCell" owner:self options:nil].lastObject;
        
        [_mainPhotosCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        [self.mainPhotosCell changeTitle:LZLocalizedString(@"res_photo_title", @"")];
        
        [self.mainPhotosCell loadImages:@[]];
        
        
        @weakify(self)
        [_mainPhotosCell setTapPictureBlock:^(NSInteger index, UIImageView *contentImageView) {
            @strongify(self)
            
            MJPhoto *photo = self.brower.photos[index];
            
            photo.srcImageView = contentImageView; //设置来源哪一个UIImageView
            
            self.brower.currentPhotoIndex = index;
            
            [self.brower show];
        }];
        
        [_mainPhotosCell setAddPictureBlock:^{
            @strongify(self)
            
            if (self.mainPhotos.count >= 5) {
                [self showErrorForOverMaxCount];
            }
            
            [self.actionSheet ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"change_takephoto", nil), LZLocalizedString(@"res_auth_phone_album", nil),LZLocalizedString(@"person_choose_restaurant_photo", nil)], @[LZLocalizedString(@"cancel", nil)]]];
            [self.actionSheet ShowView];
        }];
        
        
        [_mainPhotosCell setDeletePictureBlock:^(NSString *imageId) {
            @strongify(self)
            [self deletePicture:imageId];
        }];
    }
    
    return _mainPhotosCell;
}


- (void)setup {
    self.backgroundColor = UIColorFromRGB(0xf9f7f7,1);
    self.separatorColor = [UIColor clearColor];
    self.dataSource = self;
    self.delegate = self;
    

    
    _brower = [[MJPhotoBrowser alloc] init];
    
    
    
    [self configData];

}


-(void)configData{
    
    _mainPhotos = @[].mutableCopy;

    
    [self requestMainPhotoData];
}


-(void)requestMainPhotoData{
    LZManagePicturePresenter *presenter = [LZManagePicturePresenter new];
    
    [presenter getMainPhotoPictureWithSellid:[LZUserModel Instance].sellerId Success:^(id data) {
        [self processPictureOperationRefrsh:data];
    } Failure:^(NSString *fail) {
        DLog(@"%@",fail);
    }];
}


/**
 上传图片文件
 
 @param img 图片
 */
- (void)uploadImg:(UIImage *)img
{
    //上传头像
    LZUploadImagePresenter *uploadImagePresenter = [[LZUploadImagePresenter alloc] init];
//    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    @weakify(self);
    [uploadImagePresenter uploadImage:img
                        andBusinessId:[LZUserModel Instance].sellerId
                      andBusinessType:@"4"
                        andBusinessNo:@"1"
                           andIsThumb:YES
                              andSize:CGSizeZero
                         andonSuccess:^(id data) {
                             @strongify(self);
                             //上传成功获取路径
                             NSArray *resultArray = data[@"data"];
                             if (resultArray.count>0) {
                                 NSDictionary *dic = resultArray[0];
                                 NSString *smallFilePath = dic[@"imgMinPath"];
                                 NSString *bigFilePath = dic[@"filePath"];
                                 NSString *imageUrlAggregation = [NSString stringWithFormat:@"%@&&%@",smallFilePath,bigFilePath];
                                 
                                 [self addPicture:imageUrlAggregation];
                             }
//                             [self stopLoadingViewForView:self.view];
                             
                         } onFail:^(NSString *fail) {
                             
//                             [self stopLoadingViewForView:self.view];
                             [self uploadLicenseFailureAction];
                             
                         }];
}

/**
 上传图片地址到后台
 
 @param imageUrlAggregation 拼合的缩略图和原图的地址  e.g. xxxx && xxxx
 */
-(void)addPicture:(NSString *)imageUrlAggregation{
    LZManagePicturePresenter *picturePresenter = [LZManagePicturePresenter new];
    
    [picturePresenter addPictureWithSellId:[LZUserModel Instance].sellerId andPhotoType:[NSString stringWithFormat:@"%d",4] andPhotoUrls:@[imageUrlAggregation] andToken:[LZUserModel Instance].userToken Success:^(id data) {
        
        [self requestMainPhotoData];
    } Failure:^(NSString *fail) {
        DLog(@"%@",fail);
        
        if ([fail isEqualToString:@"0400026"]) {
            [self showErrorForOverMaxCount];
        }
    }];
}


-(void)deletePicture:(NSString *)imageId{
    LZManagePicturePresenter *picturePresenter = [LZManagePicturePresenter new];
    
    [picturePresenter deletePictureWithSellId:[LZUserModel Instance].sellerId andPhotoIds:@[imageId] andToken:[LZUserModel Instance].userToken Success:^(id data) {
        
        [self requestMainPhotoData];
        
    } Failure:^(NSString *fail) {
        DLog(@"%@",fail);
    }];
}



-(void)processPictureOperationRefrsh:(id)data{
    //刷新
    _mainPhotos = [data mutableCopy];
    
    NSMutableArray *photos = [NSMutableArray array];
    
    [self.mainPhotos enumerateObjectsUsingBlock:^(NSDictionary *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,obj[@"maxPhoto"]]];
        [photos addObject:photo];
    }];
    
    self.brower.photos = photos;
    
    
    //刷新cell
    [self.mainPhotosCell loadImages:_mainPhotos];
    
    [self reloadData];
}


/**
 显示错误提醒 ，关于超过5张图片的。
 */
-(void)showErrorForOverMaxCount{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabel.text = LZLocalizedString(@"error_over_max_count_5", nil);
    [hud showAnimated:YES];
    [hud hideAnimated:YES afterDelay:2.5];
}


/**
 执照提交失败,从新提交
 */
- (void)uploadLicenseFailureAction
{
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_license_upload_failure", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    @weakify(self)
    alert.clickButtonIndexBlock = ^(NSInteger index){
        @strongify(self)
        if (index == 1) {
            if (self.resultImage) {
                [self uploadImg:self.resultImage];
            }
        }
    };
}




#pragma
#pragma mark UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 5;
    }else if (section == 1) {
        return 2;
    }else{
        return self.groupListArrays.count + 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(section == 2) {
        return 55.0f;
    }
    
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 100.0f;
    }else if (section == 1) {
        return 10.0f;
    }else{
        return 0.001;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            return [LZMyRestaurantInfoTableViewCell getCellSizeWithText:self.merchantInfoModel.cookingStyle] + 65;
        }else if (indexPath.row == 3){
            return [LZMyRestaurantInfoTableViewCell getCellSizeWithText:self.merchantInfoModel.restaurantAddress] + 65;
        }else {
            return 55.0f;
        }
    }else if (indexPath.section == 1) {
        return 55.f;
    }else {
        if (indexPath.row == self.groupListArrays.count) {
            return [LZMainPhotosOperationTableViewCell getCellHeight:self.mainPhotos.count boundNumber:5] + 40;
        }
        
        return 55.0f;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    @weakify(self)
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 4) {   //name //Restaurant address //phone
            LZMyRestaurantInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"singleCellIdentifier"];
            if (!cell) {
                cell = [[LZMyRestaurantInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                              reuseIdentifier:@"singleCellIdentifier"
                                                                      andType:LZ_MyRESTAURANT_CELLTYPE_SINGLE];
            }
            
            cell.tag = indexPath.row;
            [cell setModel:self.merchantInfoModel];
            
            return cell;
        }else if (indexPath.row == 3) {
            LZMyRestaurantInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"imageCellIdentifier"];
            if (!cell) {
                cell = [[LZMyRestaurantInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                              reuseIdentifier:@"imageCellIdentifier"
                                                                      andType:LZ_MyRESTAURANT_CELLTYPE_IMAGE];
            }
            
            cell.tag = indexPath.row;
            [cell setModel:self.merchantInfoModel];
            
            return cell;
        }else {
            LZMyRestaurantInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"doubleCellIdentifier"];
            if (!cell) {
                cell = [[LZMyRestaurantInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                              reuseIdentifier:@"doubleCellIdentifier"
                                                                      andType:LZ_MyRESTAURANT_CELLTYPE_DOUBLE];
            }
            
            cell.tag = indexPath.row;
            [cell setModel:self.merchantInfoModel];
            
            return cell;
        }
    }else if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            LZMyRestaurantInfoTextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textFieldCellIdentifier"];
            if (!cell) {
                cell = [[LZMyRestaurantInfoTextFieldTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                                       reuseIdentifier:@"textFieldCellIdentifier"];
            }
            
            [cell setMerchantInfoModel:self.merchantInfoModel];
            cell.textFieldEditDidEndBlock = ^(NSString * text, NSInteger tag,NSIndexPath *indexP) {
                @strongify(self)
                if(self.textFieldEditDidEndBlock) {
                    self.textFieldEditDidEndBlock([text floatValue]);
                }
            };
            
            return cell;
        }else {
            LZMyRestaurantInfoTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"timeCellIdentifier"];
            if (!cell) {
                cell = [[LZMyRestaurantInfoTimeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                                  reuseIdentifier:@"timeCellIdentifier"];
            }
            
            [cell setMerchantInfoModel:self.merchantInfoModel];
            cell.tapGRActionBlock = ^(id sender){
                @strongify(self)
                if (self.tapGRActionBlock) {
                    self.tapGRActionBlock(indexPath, sender);
                }
            };
            
            return cell;
        }
    }else {
        
        if (indexPath.row != self.groupListArrays.count) {
            LZGroupListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"groupListCellIdentifier"];
            if (!cell) {
                cell = [[LZGroupListTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                       reuseIdentifier:@"groupListCellIdentifier"];
            }
            
            [cell setModel:self.groupListArrays[indexPath.row]];
            cell.didEditButtonBlock = ^(id sender) {
                if (self.didEditSelectRowBlock) {
                    self.didEditSelectRowBlock(indexPath);
                }
            };
            
            cell.didDeleteButtonBlock = ^(id sender) {
                if (self.didDeleteSelectRowBlock) {
                    self.didDeleteSelectRowBlock(indexPath);
                }
            };
            
            return cell;
        }else{
 
            return self.mainPhotosCell;
        }
    }
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 2) {
        return self.headerView;
    }
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        
        UIView * v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
        v.backgroundColor = UIColorFromRGB(0xf8f8f8, 1);
        
        UILabel * textlabel = [[UILabel alloc] init];
        textlabel.font = [UIFont systemFontOfSize:12];
        textlabel.textColor = UIColorFromRGB(0xbababa, 1);
        textlabel.numberOfLines = 0;
        [v addSubview:textlabel];
        
        NSString * str = LZLocalizedString(@"tip_message", nil);
        
        NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:str];
        NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle1 setLineSpacing:3];
        [attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [str length])];
        [textlabel setAttributedText:attributedString1];
        
        [textlabel makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(15);
            make.leading.mas_equalTo(15);
            make.trailing.mas_equalTo(-15);
            make.bottom.mas_equalTo(-15);
        }];
        
        return v;
    }
    
    return nil;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.groupListArrays.count) {
        return;
    }

    
    if(_didSelectRowBlock) {
        _didSelectRowBlock(indexPath);
    }
}

#pragma
#pragma mark LZPictureManagerDelegate

-(void)LZPictureManagerFinishPickingMediaWithInfo:(NSDictionary *)info{
    self.resultImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (self.resultImage) {
        [self uploadImg:self.resultImage];
    }
}

@end
